package com.hdu.handler;

import com.alibaba.fastjson.JSON;
import com.hdu.dto.UserInfoDTO;
import com.hdu.entity.LoginLog;
import com.hdu.entity.UserAuth;
import com.hdu.mapper.LoginLogMapper;
import com.hdu.mapper.UserAuthMapper;
import com.hdu.pojo.Result;
import com.hdu.util.BeanCopyUtils;
import com.hdu.util.JwtUtils;
import com.hdu.util.UserUtils;
import lombok.RequiredArgsConstructor;
import org.fusesource.jansi.Ansi;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 登录成功处理
 *
 * @author xiaobai
 * @since 2024/05/20
 */
@Component
@RequiredArgsConstructor
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    private final UserAuthMapper userAuthMapper;

    private final LoginLogMapper loginLogMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        // 返回登录信息
        UserInfoDTO userLoginDTO = BeanCopyUtils.copyObject(UserUtils.getLoginUser(), UserInfoDTO.class);
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userLoginDTO.getUsername());

        //jwt包含了当前登录的用户信息
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(Result.success(JwtUtils.generateJwt(claims))));
        // 更新用户ip，最近登录时间
        updateUserInfo();
        // 登录日志
        LoginLog loginLog = UserUtils.getLoginLog(UserUtils.getLoginUser());
        loginLog.setStatus(1);
        loginLog.setMessage("登录成功");
        System.out.println("登录日志：" + loginLog);
//        loginLogMapper.insert(loginLog);
    }

    /**
     * 更新用户信息
     */
    @Async
    public void updateUserInfo() {
        UserAuth userAuth = UserAuth.builder()
                .id(UserUtils.getLoginUser().getId())
                .ipAddress(UserUtils.getLoginUser().getIpAddress())
                .ipSource(UserUtils.getLoginUser().getIpSource())
                .lastLoginTime(UserUtils.getLoginUser().getLastLoginTime())
                .build();
        userAuthMapper.updateById(userAuth);
    }

}
